<?php
class ControllerCatalogProduct extends AdminController {

  	public function index() {
		M('catalog/product');

		$this->getList();
  	}

  	public function insert() {

		M('catalog/product');

    	if ($this->request->isPost() && $this->validateForm()) {			
			$this->model_catalog_product->addProduct($this->request->post);

			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('catalog/product'));
    	}

    	$this->getForm();
  	}

  	public function update() {

		M('catalog/product');

    	if ($this->request->isPost() && $this->validateForm()) {
			$this->model_catalog_product->editProduct($this->request->get['product_id'], $this->request->post);

			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('catalog/product'));
		}

    	$this->getForm();
  	}
	
	public function update_status() {
		if (isset($this->request->post['selected'])) {
			$status = P('status', 1);
			$product_ids = implode(',', $this->request->post['selected']);
			$this->db->query("UPDATE @@product SET status=$status WHERE product_id IN ($product_ids)");
			$this->session->set_flashdata('success', $this->_['text_success']);			
		}
		
		$this->redirect(UA('catalog/product'));
	}
	
  	public function delete() {

		M('catalog/product');

		if (isset($this->request->post['selected'])) {
			foreach ($this->request->post['selected'] as $product_id) {
				$this->model_catalog_product->deleteProduct($product_id);
	  		}

			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('catalog/product'));
		}

    	$this->getList();
  	}

  	public function copy() {

		M('catalog/product');

		if (isset($this->request->post['selected']) && $this->validateCopy()) {
			foreach ($this->request->post['selected'] as $product_id) {
				$this->model_catalog_product->copyProduct($product_id);
	  		}

			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('catalog/product'));
		}

    	$this->getList();
  	}

  	public function smartedit() {
  		if ($this->hasMP()) {
	  		$product_id = (int) G('id');
	  		$field = G('field');
	  		$value = G('val');
	  		if ($field == 'name') {
	  			$rs = $this->db->update('product_description', array($field => $value), "product_id=$product_id AND language_id=" . C('config_language_id'));
	  		}
	  		else {
	  			$rs = $this->db->update('product', array($field => $value), "product_id=$product_id");
	  		}
  		}
  		else $rs = 0;
  		$this->response->setOutput(json_encode(array('status' => $rs)));
  	}
  	
  	protected function getList() {
		$this->document->setTitle($this->_['heading_title']);
		
		M('catalog/category');		
		$this->data['categories'] = $this->model_catalog_category->getCategories(0, true, 0);
		
		M('catalog/supplier');		
		$this->data['suppliers'] = $this->model_catalog_supplier->getSupplierOptions();

		M('tool/image');

		$qf = new Query_filter('product_query_filter');
		$this->data['products'] = $this->model_catalog_product->getProducts($qf, $product_total);

		$global_discount_rate = 0;
		if (C('config_use_global_discount')) {
			$rates = C('config_global_discount_rates');
			$customer_group_id = C('config_customer_group_id');
			if (isset($rates[$customer_group_id])) {
				foreach($rates[$customer_group_id] as $k => $v) {
					if ($k == 1) {
						$global_discount_rate = $v;
						break;
					}
				}
			}
		}

		foreach ($this->data['products'] as $i => $result) {
			$special = false;
			$product_specials = $this->model_catalog_product->getProductSpecials($result['product_id']);
			foreach ($product_specials  as $product_special) {
				if (($product_special['date_start'] == '0000-00-00' || $product_special['date_start'] <= date('Y-m-d')) && ($product_special['date_end'] == '0000-00-00' || $product_special['date_end'] >= date('Y-m-d'))) {
					$special = $product_special['price'];
					break;
				}
			}
			
			if ($special) {
				$this->data['products'][$i]['special'] = $special;
				$this->data['products'][$i]['promotion'] = 'S';
			}			
			elseif (!$special && $result['discount']) {
				$this->data['products'][$i]['special'] = $result['discount'];
				$this->data['products'][$i]['promotion'] = 'D';
			}
			elseif (!$special && $global_discount_rate) {
				$this->data['products'][$i]['special'] = round($result['price'] * $global_discount_rate / 100, 2);
				$this->data['products'][$i]['promotion'] = 'D';		
			}
			else {
				$this->data['products'][$i]['special'] = false;
				$this->data['products'][$i]['promotion'] = '';
			}
			$this->data['products'][$i]['image'] = thumb($result['image'], C('config_image_product_width'), C('config_image_product_height'));
			$this->data['products'][$i]['rating'] = round($result['rating']);
			$this->data['products'][$i]['href'] = HTTP_CATALOG . $result['link'];
    	}

		$this->data['pagination'] = $this->pagination($product_total)->render();
		
		//filters
		$this->data['filter_name'] = $qf->get('filter_name');
		$this->data['filter_model'] = $qf->get('filter_model');
		$this->data['filter_price'] = $qf->get('filter_price');
		$this->data['filter_quantity'] = $qf->get('filter_quantity');
		$this->data['filter_featured'] = $qf->get('filter_featured');
		$this->data['filter_status'] = $qf->get('filter_status');
		$this->data['filter_category_id'] = $qf->get('filter_category_id', 0);
		$this->data['filter_supplier_id'] = $qf->get('filter_supplier_id', 0);

        foreach($this->data['products']  as $product){
            $this->data['filter_models'][]= $product['model'];
        }

		$this->display('catalog/product_list.tpl');
  	}

  	protected function getForm() {
		$this->document->setTitle($this->_['heading_title']);
		$this->document->addScript(ROOT . 'static/javascript/jquery/jquery.validate.js');
		$this->document->addScript(ROOT . 'static/javascript/jquery/checkboxtree/jquery.checkboxtree.min.js');
		$this->document->addStyle(ROOT . 'static/javascript/jquery/checkboxtree/jquery.checkboxtree.min.css');
		
		$this->data['token'] = $this->session->data['token'];

		$product_id = G('product_id');
		
		//product info
		if ($product_id) {
			$this->data['action'] = UA('catalog/product/update', 'product_id=' . $product_id);
			if (!$this->request->isPost()) {
				$this->vo->data = $this->model_catalog_product->getProduct($product_id);
				$this->vo->data['product_description'] = $this->model_catalog_product->getProductDescriptions($product_id);
			}	
		} else {
			$this->data['action'] = UA('catalog/product/insert');
		}		

		//language
		$this->data['languages'] = C('cache_language_2');

		//product to store
		M('setting/store');
		$this->data['stores'] = $this->model_setting_store->getStores();

		if (isset($this->request->post['product_store'])) {
			$this->data['product_store'] = $this->request->post['product_store'];
		} elseif ($product_id) {
			$this->data['product_store'] = $this->model_catalog_product->getProductStores($product_id);
		} else {
			$this->data['product_store'] = array(0);
		}

		//manufacturer
		M('catalog/manufacturer');
    	$this->data['manufacturers'] = $this->model_catalog_manufacturer->getManufacturers();
		
    	//supplier
		M('catalog/supplier');		
		$this->data['suppliers'] = $this->model_catalog_supplier->getSupplierOptions();
		
		//
		M('localisation/tax_class');
		$this->data['tax_classes'] = $this->model_localisation_tax_class->getTaxClasses();

		//
		$this->data['stock_statuses'] = C('cache_stock_status');
		$this->data['weight_classes'] = C('cache_weight_class');
		$this->data['length_classes'] = C('cache_length_class');

		//attributes
		M('catalog/attribute');
		
		if (isset($this->request->post['product_attribute'])) {
			$this->data['product_attributes'] = $this->request->post['product_attribute'];
		} elseif ($product_id) {
			$this->data['product_attributes'] = $this->model_catalog_product->getProductAttributes($product_id);
		} else {
			$this->data['product_attributes'] = array();
		}
		
		//attribute group
		if ($this->data['product_attributes']) {
			$attribute_group_ids = array();
			foreach ($this->data['product_attributes'] as $product_attribute) {
				$attribute_group_ids[] = $product_attribute['attribute_group_id'];
			}
			$attribute_group_ids = array_unique($attribute_group_ids);
			$this->data['attribute_groups'] = $this->model_catalog_product->getAttributeGroupByIds($attribute_group_ids);
		}
		else $this->data['attribute_groups'] = array();
		
		
		//options
		M('catalog/option');

		if (isset($this->request->post['product_option'])) {
			$this->data['product_options'] = $this->request->post['product_option'];
		} elseif ($product_id) {
			$this->data['product_options'] = $this->model_catalog_product->getProductOptions($product_id);
		} else {
			$this->data['product_options'] = array();
		}
		
		$this->data['option_values'] = array();

		foreach ($this->data['product_options'] as $product_option) {
			if (in_array($product_option['type'], array('select', 'radio', 'checkbox', 'image'))) {
				if (!isset($this->data['option_values'][$product_option['option_id']])) {
					$this->data['option_values'][$product_option['option_id']] = $this->model_catalog_option->getOptionValues($product_option['option_id']);
				}
			}
		}

		//customer group
		M('sale/customer_group');
		$this->data['customer_groups'] = $this->model_sale_customer_group->getCustomerGroups();
		
		//discount
		if (isset($this->request->post['product_discount'])) {
			$this->data['product_discounts'] = $this->request->post['product_discount'];
		} elseif ($product_id) {
			$this->data['product_discounts'] = $this->model_catalog_product->getProductDiscounts($product_id);
		} else {
			$this->data['product_discounts'] = array();
		}
		
		//special
		if (isset($this->request->post['product_special'])) {
			$this->data['product_specials'] = $this->request->post['product_special'];
		} elseif ($product_id) {
			$this->data['product_specials'] = $this->model_catalog_product->getProductSpecials($product_id);
		} else {
			$this->data['product_specials'] = array();
		}
		
		//gifts
		$this->data['product_gifts'] = array();
		if (isset($this->request->post['product_gift'])) {
			$products = $this->request->post['product_gift'];
		} elseif ($product_id) {
			$products = $this->model_catalog_product->getProductGifts($product_id);
		} else {
			$products = array();
		}
		foreach ($products as $p) {
			$product_info = $this->model_catalog_product->getProduct($p['related_id']);

			if ($product_info) {
				$this->data['product_gifts'][] = array(
					'product_id' => $product_info['product_id'],
					'related_id' => $p['related_id'],
					'customer_group_id' => $p['customer_group_id'],
					'qty' => $p['qty'],
					'date_start' => $p['date_start'],
					'date_end' => $p['date_end'],
					'name'       => v5_substr($product_info['name'], 100),
					'model'      => $product_info['model'],
					'image'      => thumb($product_info['image'], C('config_image_product_width'), C('config_image_product_height')),
				);
			}
		}

		$this->data['product_packages'] = array();
		if (isset($this->request->post['product_package'])) {
			$products = $this->request->post['product_package'];
		} elseif ($product_id) {
			$products = $this->model_catalog_product->getProductPackages($product_id);
		} else {
			$products = array();
		}
		foreach ($products as $p) {
			$product_info = $this->model_catalog_product->getProduct($p['related_id']);

			if ($product_info) {
				$this->data['product_packages'][] = array(
					'product_id' => $product_info['product_id'],
					'related_id' => $p['related_id'],
					'customer_group_id' => $p['customer_group_id'],
					'price' => $p['price'],
					'org_price' => $product_info['price'],
					'date_start' => $p['date_start'],
					'date_end' => $p['date_end'],
					'name'       => v5_substr($product_info['name'], 100),
					'model'      => $product_info['model'],
					'image'      => thumb($product_info['image'], C('config_image_product_width'), C('config_image_product_height')),
				);
			}
		}

		//images
		if (isset($this->request->post['product_image'])) {
			$product_images = $this->request->post['product_image'];
		} elseif ($product_id) {
			$product_images = $this->model_catalog_product->getProductImages($product_id);
		} else {
			$product_images = array();
		}

		$this->data['product_images'] = array();

		foreach ($product_images as $product_image) {
			if ($product_image['image'] && file_exists(DIR_IMAGE . $product_image['image'])) {
				$image = $product_image['image'];
			} else {
				$image = 'no_image.jpg';
			}

			$this->data['product_images'][] = array(
				'image'      => $image,
				'thumb'      => thumb($image),
				'sort_order' => $product_image['sort_order']
			);
		}

		$this->data['no_image'] = thumb();

		//download
		M('catalog/download');
		$this->data['downloads'] = $this->model_catalog_download->getDownloads();

		if (isset($this->request->post['product_download'])) {
			$this->data['product_download'] = $this->request->post['product_download'];
		} elseif ($product_id) {
			$this->data['product_download'] = $this->model_catalog_product->getProductDownloads($product_id);
		} else {
			$this->data['product_download'] = array();
		}
		
		//category
		M('catalog/category');
		$this->data['category_tree'] = $this->model_catalog_category->getCategoryTree();
		
		if (isset($this->request->post['product_category'])) {
			$this->data['product_category'] = $this->request->post['product_category'];
		} elseif ($product_id) {
			$this->data['product_category'] = $this->model_catalog_product->getProductCategories($product_id);
		} else {
			$this->data['product_category'] = array();
		}
		
		//related product
		if (isset($this->request->post['product_related'])) {
			$products = $this->request->post['product_related'];
		} elseif ($product_id) {
			$products = $this->model_catalog_product->getProductRelated($product_id);
		} else {
			$products = array();
		}

		$this->data['product_related'] = array();

		foreach ($products as $_product_id) {
			$related_info = $this->model_catalog_product->getProduct($_product_id);

			if ($related_info) {
				$this->data['product_related'][] = array(
					'product_id' => $related_info['product_id'],
					'name'       => v5_substr($related_info['name'], 100),
					'model'      => $related_info['model'],
					'image'      => thumb($related_info['image'], C('config_image_product_width'), C('config_image_product_height')),
				);
			}
		}
		
		//reward
		if (isset($this->request->post['product_reward'])) {
			$this->data['product_reward'] = $this->request->post['product_reward'];
		} elseif ($product_id) {
			$this->data['product_reward'] = $this->model_catalog_product->getProductRewards($product_id);
		} else {
			$this->data['product_reward'] = array();
		}
		
		//layout
		M('design/layout');
		$this->data['layouts'] = $this->model_design_layout->getLayouts();

		if (isset($this->request->post['product_layout'])) {
			$this->data['product_layout'] = $this->request->post['product_layout'];
		} elseif ($product_id) {
			$this->data['product_layout'] = $this->model_catalog_product->getProductLayouts($product_id);
		} else {
			$this->data['product_layout'] = array();
		}
		
		$this->display('catalog/product_form.tpl');
  	}
	
  	protected function validateForm() {
		$this->load->library('form_validation', true);
    	foreach ($this->request->post['product_description'] as $language_id => $value) {
			$this->form_validation->set_rules("product_description[$language_id][name]", '', 'required|range_length[3,255]', $this->_['error_name']);
    	}
		$this->form_validation->set_rules('model', '', 'required|range_length[3,64]', $this->_['error_model']);

		if ($this->form_validation->run()) {
			return true;
		}
		else {
			$this->setMessage('error_warning', $this->_['error_warning']);
			return false;
		}
  	}

  	protected function validateCopy() {
    	if (!$this->hasMP()) {
      		$this->setMessage('error_warning', $this->_['error_permission']);
			return false;
    	}

		return true;
  	}

	public function autocomplete() {
		$json = array();

		if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_model']) || isset($this->request->get['filter_category_id'])) {
			M('catalog/product');

			$qf = new Query_filter(null, false);
			$results = $this->model_catalog_product->getProducts($qf, $total);

			foreach ($results as $result) {
				$option_data = array();

				$product_options = $this->model_catalog_product->getProductOptions($result['product_id']);

				foreach ($product_options as $product_option) {
					if ($product_option['type'] == 'select' || $product_option['type'] == 'radio' || $product_option['type'] == 'checkbox' || $product_option['type'] == 'image') {
						$option_value_data = array();
						foreach ($product_option['product_option_value'] as $product_option_value) {
							$product_option_value['price'] = (float)$product_option_value['price'] ? $this->currency->format($product_option_value['price'], C('config_currency')) : false;
							$option_value_data[] = $product_option_value;
						}
						$product_option['option_value'] = $option_value_data;
						unset($product_option['product_option_value']);
					}
					
					$option_data[] = $product_option;
				}

				$json[] = array(
					'product_id' => $result['product_id'],
					'name'       => v5_substr($result['name'], 100),
					'model'      => $result['model'],
					'option'     => $option_data,
					'price'      => $result['price'],
					'image'      => thumb($result['image'], C('config_image_product_width'), C('config_image_product_height'))
				);
			}
		}

		$this->response->setOutput(json_encode($json));
	}
}
?>